Install `npm` packages globally without sudo on macOS and Linux
By default, npm
installs packages locally within your project directory. While you can install packages globally using npm install -g <package>
(which is useful for command-line tools), this typically requires root privileges or using sudo
.
Having to use sudo
for global package installation is not ideal from a security perspective. Additionally, it can cause permission issues when managing packages.
Let's explore how to install npm packages globally without sudo privileges
1. Create a directory for global packages
mkdir "${HOME}/.npm-global"
2. Tell npm
where to store globally installed packages
npm config set prefix "${HOME}/.npm-global"
3. Ensure npm
will find installed binaries and man pages
Add the following to your .bashrc
/.zshrc
:
NPM_PACKAGES="${HOME}/.npm-global" export PATH="$PATH:$NPM_PACKAGES/bin" # Preserve MANPATH if you already defined it somewhere in your config. # Otherwise, fall back to `manpath` so we can inherit from `/etc/manpath`. export MANPATH="${MANPATH-$(manpath)}:$NPM_PACKAGES/share/man"
If you're using fish
, add the following to ~/.config/fish/config.fish
:
set NPM_PACKAGES "$HOME/.npm-global" set PATH $PATH $NPM_PACKAGES/bin set MANPATH $NPM_PACKAGES/share/man $MANPATH
If you have erased your MANPATH by mistake, you can restore it by running set -Ux MANPATH (manpath -g) $MANPATH
once. Do not put this command in your config.fish
.
Check out npm-g_nosudo
for doing the above steps automagically
NOTE: If you are running macOS, the .bashrc
file may not yet exist, and the terminal will be obtaining its environment parameters from another file, such as .profile
or .bash_profile
. These files also reside in the user's home folder. In this case, simply adding the following line to them will instruct Terminal to also load the .bashrc
file:
source ~/.bashrc
See also: npm
's documentation on "Fixing npm
permissions".
Community
We're excited to see the community adopt Hyperse-io, raise issues, and provide feedback. Whether it's a feature request, bug report, or a project to showcase, please get involved!